<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         :title="IsEdit ? '编辑菜单' : '新增菜单'"
         width="700"
         @close="handleClose"
      >
         <el-form
            :model="form"
            :rules="rules"
            ref="formRef"
            label-width="200px"
         >
            <el-row :gutter="20">
               <el-col :span="24">
                  <el-form-item
                     label="上级菜单"
                     required
                  >
                     <el-select
                        v-model="form.parent_id"
                        placeholder="请选择"
                        :disabled="!IsEdit"
                     >
                        <el-option
                           v-for="item in selectMenuList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"
                        />
                     </el-select>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="菜单类型"
                     required
                  >
                     <el-radio-group
                        v-model="form.type"
                        placeholder="请选择"
                     >
                        <el-radio
                           v-for="item in menuTypeOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"
                        />
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="菜单图标"
                     prop="icon"
                     required
                  >
                     <el-input
                        :prefix-icon="form.icon"
                        v-model.trim="form.icon"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="权限标识"
                     required
                  >
                     <el-input
                        v-model.trim="form.auth_code"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="菜单名称"
                     required
                  >
                     <el-input
                        v-model.trim="form.name"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="菜单排序"
                     required
                  >
                     <el-input
                        type="number"
                        v-model="form.show_sort"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item
                     label="路由地址"
                     required
                  >
                     <el-input
                        v-model.trim="form.paths"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item
                     label="对应接口"
                     required
                  >
                     <el-input
                        v-model.trim="form.route_urls"
                        placeholder="请输入"
                     />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row :gutter="20"> </el-row>
            <el-row :gutter="20">
               <el-col :span="12">
                  <el-form-item label="菜单状态">
                     <el-radio-group
                        v-model="form.status"
                        placeholder="请选择"
                     >
                        <el-radio
                           v-for="item in statusOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"
                        />
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="handleClose">取消</el-button>
               <el-button
                  color="#6860ff"
                  @click="handleSubmit"
               >
                  确定
               </el-button>
            </div>
         </template>
      </el-dialog>
   </div>
   <Select_a_Superior
      ref="selectSuperiorRef"
      @selectPurchasingDirector=""
   />
</template>

<script setup lang="ts">
   import { ref, reactive, defineEmits } from "vue";
   import Select_a_Superior from "./Select_a_Superior.vue";
   import { ElMessage, type FormInstance, type FormRules } from "element-plus";
   import api from "@/api/index.js";
   import MenuList from "../systemSettings.ts";
   const emit = defineEmits(["getMenuList"]);
   // 接收父组件传入的值
   const props = defineProps({});
   const selectSuperiorRef = ref<any>(null);
   const formRef = ref<FormInstance>();
   const dialogVisible = ref<boolean>(false);
   const IsEdit = ref<boolean>(true); //是否编辑
   // 表单验证规则
   const rules = reactive<FormRules>({
      parentMenu: [{ required: true, message: "请选择上级菜单", trigger: "change" }],
      menuType: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
      icon: [{ required: true, pattern: /^[A-Z][a-zA-Z]*$/, message: "请输入菜单图标,必须是英文字母且第一个字母必须为大写", trigger: "change" }],
      menuName: [
         { required: true, message: "请输入菜单名称", trigger: "blur" },
         { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
      ],
      orderNum: [
         { required: true, message: "请输入菜单排序", trigger: "blur" },
         { type: "number", message: "必须为数字值", trigger: "blur" },
      ],
      routeParam: [{ required: true, message: "请输入路由参数", trigger: "blur" }],
      routeAddress: [
         { required: true, message: "请输入路由地址", trigger: "blur" },
         { pattern: /^\//, message: "路由地址必须以/开头", trigger: "blur" },
      ],
      isExternalLink: [{ required: true, message: "请选择是否外链", trigger: "change" }],
      isCache: [{ required: true, message: "请选择是否缓存", trigger: "change" }],
   });
   let form = ref<MenuList>({
      id: 0,
      parent_id: 0,
      auth_code: "",
      name: "",
      type: 0,
      icon: "",
      paths: "",
      route_urls: "",
      buttons: "",
      status: 0,
      show_sort: 0,
   });
   interface MenuItem {
      id: number;
      name: string;
      children?: MenuItem[];
   }

   const selectMenuList = ref<MenuItem[]>([]);

   const getMenuList = async () => {
      const res = await api.authority.getAuthList({});
      let arr: MenuItem[] = [{ id: 0, name: "顶级菜单" }];

      if (Array.isArray(res.data)) {
         res.data.forEach((item: any) => {
            // 添加父菜单
            arr.push({
               id: item.id,
               name: item.name,
            });

            // 处理子菜单
            if (item.children && item.children.length > 0) {
               item.children.forEach((child: any) => {
                  arr.push({
                     id: child.id,
                     name: child.name,
                  });
               });
            }
         });
      }

      selectMenuList.value = arr;

      // 确保在获取数据后立即设置form.id
      if (arr.length > 0) {
         form.value.parent_id = arr[0].id;
      }
   };

   // 菜单类型选项
   const menuTypeOptions = [
      { label: "菜单", value: 1 },
      { label: "按钮", value: 2 },
      { label: "路由", value: 3 },
   ];
   // 菜单状态选项
   const statusOptions = [
      { label: "启用", value: 1 },
      { label: "禁用", value: 0 },
   ];
   // 获取权限详情
   const getAuthDetail = async (id: number) => {
      const res = await api.authority.getAuthDetail({ id: form.value.id });
      if (res.code === 200) {
         form.value = { ...res.data };
      }
   };

   // 打开选择直属上级弹窗
   const openLoading = async (id: number | null = null, isEdit = true) => {
      try {
         // 重置表单状态
         form.value = {} as MenuList;
         IsEdit.value = isEdit;

         // 获取菜单列表
         await getMenuList();

         // 处理不同场景
         if (!id) {
            // 新建菜单
            dialogVisible.value = true;
            return;
         }

         if (isEdit) {
            // 编辑现有菜单
            form.value.id = id;
            await getAuthDetail(id);
         } else {
            // 添加子菜单
            form.value.parent_id = id;
         }

         dialogVisible.value = true;
      } catch (error) {
         console.error("打开菜单弹窗失败:", error);
         // 这里可以添加错误提示
      }
   };
   // 添加权限
   const addAuth = async () => {
      const res = await api.authority.addAuth(form.value);
      if (res.code === 200) {
         ElMessage.success("添加权限成功");
         emit("getMenuList");
      }
   };
   // 编辑权限
   const editAuth = async () => {
      const res = await api.authority.editAuth({ ...form.value, id: form.value.id });
      if (res.code === 200) {
         ElMessage.success("编辑权限成功");
         emit("getMenuList");
      }
   };
   const handleSubmit = async () => {
      const params = {
         parent_id: form.value.parent_id,
         auth_code: form.value.auth_code,
         name: form.value.name,
         type: form.value.type,
         icon: form.value.icon,
         paths: form.value.paths,
         route_urls: form.value.route_urls,
         status: form.value.status,
         show_sort: form.value.show_sort,
      };
      if (!formRef.value) return;
      if (form.value.id) {
         await editAuth();
      } else {
         await addAuth();
      }
      dialogVisible.value = false;
   };

   // 重置表单
   const resetForm = () => {
      if (!formRef.value) return;
      formRef.value.resetFields();
   };

   // 关闭弹窗时重置表单
   const handleClose = () => {
      resetForm();
      dialogVisible.value = false;
   };

   defineExpose({
      openLoading,
   });
</script>

<style lang="scss" scoped>
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 10px 30px;
   }
   :deep(.el-form-item__label) {
      justify-content: flex-start;
   }
   :deep(.el-form-item) {
      flex-direction: column;
      margin-bottom: 7px;
   }
   :deep(.el-select__wrapper) {
      background: #fafcfb;
   }
   :deep(.el-badge__content.is-fixed) {
      color: #666;
      border-radius: 3px;
      padding: 4px;
   }
   :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
      width: 100%;
   }
   :deep(.el-button:hover) {
      color: #6860ff;
      background: #f4f5f7;
   }
   :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 1px #6860ff;
   }
   :deep(.el-select__wrapper.is-focused) {
      box-shadow: 0 0 0 1px #6860ff !important;
   }
   .supply-products {
      margin-top: 20px;
      .title {
         display: flex;
         align-items: center;
         justify-content: space-between;
         margin-bottom: 16px;
         font-weight: bold;
         .title-text {
            display: flex;
            align-items: center;
            .line {
               height: 17px;
               width: 2px;
               border-radius: 12px;
               margin-right: 8px;
               background-color: #6860ff;
            }
         }
      }
   }
   .image-list {
      display: flex;
      gap: 8px;
      .el-image {
         width: 40px;
         height: 40px;
         border-radius: 4px;
      }
   }
</style>
